<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/15
 * Time: 11:10
 */

namespace app\common\mysic\notify\entity;


use app\common\mysic\MysicBase;

class WeiXinEntity extends MysicBase implements PayCallbackEntityInterface
{
    protected $xmlData;
    protected $data;

    public function __construct(string $xml)
    {
        parent::__construct();
        if($this->isEmpty($xml)){
            throw new \Exception('XML数据为空');
        }
        if(!$this->isValid($xml)){
            throw new \Exception('XML数据格式不合法');
        }
        $this->xmlData = $xml;
        libxml_disable_entity_loader(true);
        $this->data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    private function isEmpty($xml)
    {
        return empty($xml);
    }

    private function isValid($xml)
    {
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$xml,true)){
            xml_parser_free($xml_parser);
            return false;
        }else {
            return true;
        }
    }

    public function isSuccess(): bool
    {
        return $this->data['result_code'] == 'SUCCESS';
    }

    public function getAmount(): int
    {
        return $this->data['total_fee'];
    }

    public function getOrderNo(): string
    {
        return $this->data['out_trade_no'];
    }

    public function getThirdOrderNo(): string
    {
        return $this->data['transaction_id'];
    }

    public function getAppId(): string
    {
        return $this->data['appid'];
    }

    public function getResultCode(): string
    {
        return $this->data['result_code'];
    }

    public function getOrigin(): string
    {
        return $this->xmlData;
    }

    public function getData(): array
    {
        return $this->data;
    }

    public function getReturnCode():string
    {
        return $this->data['return_code'];
    }

    public function getAttach():string
    {
        return $this->data['attach'];
    }
}